//
//  CommitOrderViewController.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/6/30.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "CommitOrderViewController.h"

#import "CommitOrderAddressTableViewCell.h"//填写地址cell
#import "CommitOrderPackageTableViewCell.h"//包裹cell
#import "CommitOrderTotalTableViewCell.h"//合计cell
#import "CommitOrderFooterTotalString.h"//合计富文本

#import "CommitFooterView.h"//页脚View
#import "PatternOfPaymentView.h"//支付方式View

#import "AddressManagerViewController.h"//选择地址

#import "CartModel.h"//商品Model

@interface CommitOrderViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation CommitOrderViewController
{
    
    CommitFooterView *_footerView;
    /**付款方式View*/
    PatternOfPaymentView *_paymentView;
    /**付款方式背景View*/
    UIButton *_paymentbgView;
    
    NSUserDefaults *_defaults;//沙盒
    
    NSMutableArray *_remarkArray;
    
    float _total;
}

 static NSString *const CommitOrderAddressTableViewCellID = @"CommitOrderAddressTableViewCell";
 static NSString *const CommitOrderPackageTableViewCellID = @"CommitOrderPackageTableViewCell";
 static NSString *const CommitOrderTotalTableViewCellID = @"CommitOrderTotalTableViewCell";
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //设置页脚
    [self setFooterView];
}

- (void)viewWillDisappear:(BOOL)animated{
    [_paymentView removeFromSuperview];
    [_footerView removeFromSuperview];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _defaults = [NSUserDefaults standardUserDefaults];
    
    _total = 0.00;
    for (CartModel *model in _packageArray) {
        _total += [model.price floatValue];
    }
    
    //设置导航栏
    [self setNav];
    
    
    
    //注册TableView
    [self setTableView];
    
}
#pragma mark === 设置导航栏 ===
- (void)setNav{
    self.title = @"提交订单";
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}


#pragma mark === 设置页脚 ===
- (void)setFooterView{
    _footerView = [[CommitFooterView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50)];
    _footerView.backgroundColor = [UIColor whiteColor];
    _footerView.total = [NSString stringWithFormat:@"%.2f", _total];
    _footerView.freight = @"0.00";
    __weak __typeof__ (self) weakSelf = self;
    _footerView.commitOrderClick = ^(){
        [weakSelf commitOrder];
    };
    [_footerView setView];
    [[UIApplication sharedApplication].keyWindow addSubview:_footerView];
}

#pragma mark === 注册TableView ===
- (void)setTableView{
    [self.tableView registerNib:[UINib nibWithNibName:@"CommitOrderAddressTableViewCell" bundle:nil] forCellReuseIdentifier:CommitOrderAddressTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CommitOrderPackageTableViewCell" bundle:nil] forCellReuseIdentifier:CommitOrderPackageTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CommitOrderTotalTableViewCell" bundle:nil] forCellReuseIdentifier:CommitOrderTotalTableViewCellID];
}

#pragma mark === TableViewDelegate ===
//section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 1;
        case 1:
            return _packageArray.count;
        case 2:
            return 1;
        default:
            return 0;
    }
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 50;
        case 1:
            return 186;
        case 2:
            return 169;
        default:
            return 0;
    }
}
//cellForRow
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //地址
    if (indexPath.section == 0) {
        CommitOrderAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CommitOrderAddressTableViewCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    
    //商品
    }else if (indexPath.section == 1){
        if (!_remarkArray) {
            _remarkArray = [NSMutableArray array];
        }else if (_remarkArray.count == _packageArray.count){
            [_remarkArray removeAllObjects];
        }
        
        CartModel *model = _packageArray[indexPath.row];
        CommitOrderPackageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CommitOrderPackageTableViewCellID];
        cell.packageNum.text = [NSString stringWithFormat:@"包裹%ld", indexPath.row + 1];
        [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:model.IMGURL]];
        cell.goodsName.text = model.goodsName;
        cell.goodsStyle.text = model.colorAndSize;
        cell.goodsPrice.text = [NSString stringWithFormat:@"¥ %@", model.price];
        cell.goodsNum.text = [NSString stringWithFormat:@"x%@", model.num];
        
        if (_remarkArray.count < _packageArray.count) {
            [_remarkArray addObject:cell.remark];
        }else{
            [_remarkArray replaceObjectAtIndex:indexPath.row withObject:cell.remark];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    //页脚
    }else{
        CommitOrderTotalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CommitOrderTotalTableViewCellID];
        
        cell.total.attributedText = [CommitOrderFooterTotalString AttributedStringWithNum:[NSString stringWithFormat:@"%ld", _packageArray.count] andTotal:[NSString stringWithFormat:@"%.2f", _total]];
        cell.num.text = [NSString stringWithFormat:@"x%ld", _packageArray.count];
        cell.merchantPrivilege.text = @"无";
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
//selected
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        AddressManagerViewController *address = [[AddressManagerViewController alloc] init];
        address.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:address animated:YES];
    }
}


#pragma mark === 提交订单 ===
- (void)commitOrder{
    NSLog(@"确认付款");
    
    [self submitOrder];
    
//    if (!_paymentView) {
//        _paymentView = [[[NSBundle mainBundle] loadNibNamed:@"PatternOfPaymentView" owner:nil options:nil] lastObject];
//        _paymentView.frame = CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, SCREEN_HEIGHT - 50);
//        _paymentView.paymentView.frame = CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 0);
//        
//        __weak __typeof__(self) weakSelf = self;
//        _paymentView.payment = ^(int temp){
//            switch (temp) {
//                case 0:
//                    NSLog(@"选择支付宝");
//                    break;
//                case 1:
//                    NSLog(@"选择微信");
//                    break;
//                case 2:
//                    NSLog(@"选择银联");
//                    break;
//                case 3:
//                    [weakSelf hiddenPatternOfPaymentView];
//                    break;
//                default:
//                    break;
//            }
//        };
//    
//        UIWindow *window = [UIApplication sharedApplication].keyWindow;
//        [window addSubview:_paymentView];
//        [window bringSubviewToFront:_footerView];
//    }
//
//    _paymentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50);
//    _paymentView.hiddenView.hidden = NO;
//    [UIView animateWithDuration:0.3 animations:^{
//        _paymentView.paymentView.frame = CGRectMake(0, SCREEN_HEIGHT - 245 - 50, SCREEN_WIDTH, 245);
//    }];
}

#pragma mark === 移除支付方式View ===
- (void)hiddenPatternOfPaymentView{
    [UIView animateWithDuration:0.3 animations:^{
        _paymentView.paymentView.frame = CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 0);
    } completion:^(BOOL finished) {
        _paymentView.hiddenView.hidden = YES;
    }];
}

#pragma mark === 结算 ===
- (void)submitOrder{
    
    NSMutableString *remarkk = [NSMutableString stringWithFormat:@""];
    
    for (int i = 0; i < _remarkArray.count; i++) {
        UITextField *text = _remarkArray[i];
        [remarkk appendString:[NSString stringWithFormat:@"%@,", text.text]];
    }
    
    NSMutableString *SKUUU = [NSMutableString stringWithFormat:@""];
    for (int i = 0; i < _packageArray.count; i++) {
        CartModel *model = _packageArray[i];
        if (i == 0) {
            [SKUUU appendString:[NSString stringWithFormat:@"%@", model.SKU]];
        }else  [SKUUU appendString:[NSString stringWithFormat:@",%@", model.SKU]];
    }
    
    
    NSDictionary *paraments = @{
                                @"userid"     : [_defaults objectForKey:@"Id"],
                                @"userName"   : [_defaults objectForKey:@"UserName"],
                                @"remark"     : remarkk,
                                @"skuIds"     : SKUUU,
                                @"storeCode"  : @"777777",
                                @"ip"         : @"127.0.0.1",
                                @"mac"        : @"40:8D:5C:D6:2B:7A",
                                @"browser"    : @"Chrome50,Chrome,50.0",
                                @"osVer"      : @"Windows 7,Microsoft Windows NT 6.1.7601 Service Pack 1"
                                };
    
    NSLog(@"%@", paraments);
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/SubmitOrder?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        NSLog(@"%@", object[@"Message"]);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            [EBUtility prompt:@"下单成功!" with:self];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"商品搜索网络请求失败 : %@", error);
    } progress:nil];
    
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT - 80)style:UITableViewStyleGrouped];
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 10.0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
